import axios from 'axios';
import useUserInfoStore from '@/stores/user';
import { ElMessage } from 'element-plus';
import { serverLink } from '@/tools/const';
declare module 'axios' {
  interface AxiosInstance {
    (config: AxiosRequestConfig): Promise<any>;
  }
}

// const baseURL = serverLink; // Replace with your API base URL
const baseURL = '/one'; // Replace with your API base URL
const request = axios.create({
  baseURL,
  timeout: 5000, // Set a timeout for requests (optional)
  responseType: 'json', // Set the response type (optional)
});
// Add a request interceptor
request.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = "application/x-www-form-urlencoded;";
    // Modify the request config before sending it
    // For example, you can add headers or authentication tokens
    if (useUserInfoStore().getToken.length > 0) {
      config.headers['Authorization'] = 'Bearer ' + useUserInfoStore().token;
    }
    config.params = {...config.params, ...{ projectId: "jwhaabmufrbepemrsddkxq" }}
    // console.log(config);
    
    return config;
  },
  (error) => {
    // Handle request errors
    return Promise.reject(error);
  });

request.interceptors.response.use(
  (response) => {
    // Modify the response data before it's returned
    // For example, you can handle common response fields
    if (response.status !== 200) {
      // Handle non-successful responses
      return Promise.reject(response.data.message);
    }

    let data = response.data || response.data.data || {};
    if (typeof data === 'string') {
      data = JSON.parse(data);
    }
    if (data.code === 500) {
      ElMessage.error(data.msg);
      return Promise.reject(data.msg);
    }
    if (typeof data ==='object') {
      if (typeof data.list == "string") {
        data.list = JSON.parse(data.list);
      }
    }
    // console.log(data);
    
    return data;
  },
  (error) => {
    console.log(error);
    if (error.response.data.errors) {
      ElMessage.error(error.response.data.errors);
    }else {
      ElMessage.error("网络连接错误!");
    }
    // Handle response errors
    return Promise.reject(error);
  });

export default request;